package com.block.datapush.service.apipush.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class YangXinHuaAESUtil {

    private static final String CHARSET_NAME = "UTF-8";

    /**
     * 加密
     *
     * @param input  输入
     * @param aesKey 关键
     * @return {@code String}
     */
    public static String encryptAESECB(String input, String aesKey) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(aesKey.getBytes(CHARSET_NAME), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes(CHARSET_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
        return encoder.encodeToString(crypted);
    }

    /**
     * 解密
     *
     * @param input  输入
     * @param aesKey 关键
     * @return {@code String}
     */
    public static String decryptAESECB(String input, String aesKey) {
        byte[] output = null;
        try {
            java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
            SecretKeySpec skey = new SecretKeySpec(aesKey.getBytes(CHARSET_NAME), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(decoder.decode(input.getBytes(CHARSET_NAME)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(output);
    }

    public static void main(String[] args) {
        String content = "nishifengerwoshisha";
        String key = "527f16da12e7f913d6a685529fd14621";
        String s = YangXinHuaAESUtil.encryptAESECB(content, key);
        System.out.println(s);  //MI/l9f8UcaHF/cHTQQF9iJ5ZYCWM/7OFCD3xjUYZnl4=
        String str = YangXinHuaAESUtil.decryptAESECB(s, key);
        System.out.println(str); //nishifengerwoshisha
    }

}